package com.xiaouyudeguang.common.utils;

import com.xiaouyudeguang.common.collect.MapBuilder;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * map增强类
 *
 * @param <K>
 * @param <V>
 */
public class MapModel<K, V> extends LinkedHashMap<K, V> {

    public static final Map<?, ?> EMPTY_MAP = new LinkedHashMap<>();

    public MapModel() {
    }

    public MapModel(Map<K, V> map) {
        super(map);
    }

    public MapModel<K, V> set(K key, V value) {
        if (key != null && value != null) {
            put(key, value);
        }
        return this;
    }

    /**
     * 设置属性
     *
     * @return
     */
    public MapModel<K, V> set(K key, V value, V defaultValue) {
        put(key, value != null ? value : defaultValue);
        return this;
    }

    public V getValue(K key) {
        return get(key);
    }

    public String getText(K key) {
        V value = getValue(key);
        return value == null ? "" : String.valueOf(value);
    }

    public int getInteger(K key) {
        return Integer.parseInt(getText(key));
    }

    public long getLong(K key) {
        return Long.parseLong(getText(key));
    }

    public float getFloat(K key) {
        return Float.parseFloat(getText(key));
    }

    public <E> Map<String, E> getMap(K key) throws Exception {
        return JsonObject.toMap(getText(key));
    }

    public <E> List<E> getList(K key) throws Exception {
        return JsonObject.toList(getText(key));
    }

    public static <K, V> MapModel<K, V> empty() {
        return new MapModel<>();
    }

    public static <K, V> MapModel<K, V> get(K key, V value) {
        return get(MapBuilder.of(key, value));
    }

    public static <K, V> MapModel<K, V> get(Map<K, V> map) {
        return map == null ? empty() : new MapModel<>(map);
    }

    public static <K, V> MapModel<K, V> get(MapBuilder<K, V> map) {
        return map == null ? empty() : get(map.build());
    }
}
